package xyz.esion.knowledgebase.util

import cn.hutool.core.collection.CollUtil
import xyz.esion.knowledgebase.domain.ArticleTree
import xyz.esion.knowledgebase.entity.article.ArticleFolder
import xyz.esion.knowledgebase.entity.article.ArticleIndex
import java.util.stream.Collectors

/**
 * @author Esion
 * @since 2024/1/23
 */

fun listToTree(folders: List<ArticleFolder>, articles: List<ArticleIndex>): List<ArticleTree> {
    // 先处理目录
    val folderMap = folders.stream().collect(Collectors.groupingBy { e -> e.pid })
    val res = folders.filter { e -> e.pid == 0 }
        .map { e -> ArticleTree(e.id, e.name, false, ArrayList()) }
        .toList()
    folderToTree(res, folderMap)
    // 再处理文章
    val articleMap = articles.stream().collect(Collectors.groupingBy { e -> e.folder })
    articleToTree(res, articleMap)
    return res
}

private fun folderToTree(folders: List<ArticleTree>, folderMap: Map<Int, List<ArticleFolder>>) {
    for (folder in folders) {
        val temp = folderMap[folder.key]
        if (temp != null) {
            folder.children = temp.map { e -> ArticleTree(e.id, e.name, false, ArrayList()) }
                .toList()
            folderToTree(folder.children, folderMap)
        }
    }
}

private fun articleToTree(tree: List<ArticleTree>, articleMap: Map<Int, List<ArticleIndex>>) {
    for (item in tree) {
        if (item.children.isNotEmpty()) {
            articleToTree(item.children, articleMap)
        }
        val temps = articleMap[item.key]
        if (temps != null) {
            CollUtil.addAll(item.children, temps
                .map { e -> ArticleTree(e.id, e.name, true, ArrayList()) }
                .toList())
        }
    }
}